<template>
	<view class="post-detail">
		<!-- 导航栏 -->
		<view class="navBar">
			<view class="left" @click="toBack">
				<uni-icons type="back" size="24"></uni-icons>
			</view>
			<view class="center">帖子详情</view>
			<view class="right"></view>
		</view>
		<!-- 帖子详情 -->
		<view class="post-content">
			<view class="post-header">
				<view class="post-title">{{ post.title }}</view>
				<view class="post-meta">
					<text>作者ID: {{ post.userId }}</text><br>
					<text>发表时间: {{ formatDate(post.createdAt) }}</text><br>
					<text>修改时间: {{ formatDate(post.updatedAt) }}</text><br>
				</view>
			</view>
			<view class="post-body">{{ post.content }}</view>
			<!-- 互动按钮 -->
			<view class="interaction-buttons">
				<view class="interaction-item" @click="likePost">
					<uni-icons :type="likeStatus ? 'heart-filled' : 'heart'" size="30" :color="likeStatus ? '#ff5a5f' : '#ccc'"></uni-icons>
					<text>{{ formatCount(likeNum) }}</text>
				</view>
				<view class="interaction-item" @click="favoritePost">
					<uni-icons :type="favoriteStatus ? 'star-filled' : 'star'" size="30" :color="favoriteStatus ? '#ffcc00' : '#ccc'"></uni-icons>
					<text>{{ formatCount(favoriteNum) }}</text>
				</view>
			</view>
			<!-- 评论区 -->
			<view class="comments-section">
				<view class="add-comment">
					<input v-model="newCommentText" placeholder="添加评论..." />
					<button @click="submitComment">提交</button>
				</view>
				<view v-for="(comment, index) in comments" :key="index" class="comment-item">
					<text>{{ comment.userId }}:</text><br>
					<text style="float:right;">{{ formatDate(comment.createdAt) }}</text>
					<text>{{ comment.content }}</text>
					<view class="comment-actions">
						<view class="more-options" @click.stop="showCommentMenu(comment)">
							<text>...</text>
						</view>
					</view>
				</view>
			</view>
			<!-- 加载更多 -->
			<uni-load-more :status="status" :icon-size="16" :content-text="contentText"></uni-load-more>
			<!-- 弹出菜单 -->
			<uni-popup ref="commentMenuPopup" type="bottom">
				<view class="popup-menu">
					<button @click="deleteComment(selectedComment.commentId)">删除</button>
				</view>
			</uni-popup>
		</view>
	</view>
</template>
<script>
export default {
	data() {
		return {
			token: '',
			user: '',
			post: {},
			comments: [],
			newCommentText: '',
			likeNum: 0,
			likeStatus: false,
			favoriteNum: 0,
			favoriteStatus: false,
			pageNum: 1,
			pageSize: 6,
			totalPage: 0,
			status: "no-more",
			contentText: {
				contentdown: "上拉加载更多",
				contentrefresh: "正在加载",
				contentnomore:"没有更多数据"
			},
			selectedComment: null,
		}
	},
	onLoad(option) {
		this.user = uni.getStorageSync("user");
		console.log("user:",this.user);
		this.token = uni.getStorageSync("token");
		if (option) {
			this.getPostDetail(option.id);
			this.getLikeNum(option.id);
			this.getFavoriteNum(option.id);
			this.getLikeStatus(option.id);
			this.getFavoriteStatus(option.id);
			this.getComments(option.id);
			this.getTotalPage(option.id);
			uni.startPullDownRefresh();
		}
	},
	onPullDownRefresh() {
		console.log("下拉刷新");
		this.comments = [];
		this.pageNum = 1;
		this.getComments(this.post.postId);
	},
	onReachBottom() {
		console.log("上拉触底");
		if(this.pageNum > this.totalPage) {
			uni.showToast({
				icon: "none",
				title: '没有下一页数据了'
			});
			this.status = "no-more"
		} else {
			console.log("有下一页数据");
			this.pageNum++;
			this.getComments(this.post.postId);
		}
	},
	methods: {
		getPostDetail(id) {
			// 获取该帖子信息
			uni.request({
				url: `http://localhost:8080/getPostInfo`,
				method: 'GET',
				header: {
					'Authorization': this.token
				},
				data: {
					postId: id,
				},
				success: (res) => {
					this.post = res.data.data;
					console.log("post:",this.post);
				},
				fail: () => {
					uni.showToast({
						icon: "none",
						title: "获取帖子信息失败"
					});
				},
			});
		},
		getLikeNum(id) {
			uni.request({
				url: `http://localhost:8080/getLikeCount`,
				method: 'GET',
				header: {
					'Authorization': this.token
				},
				data: {
					postId: id,
				},
				success: (res) => {
					this.likeNum = res.data.data;
					console.log("likeNum:",this.likeNum);
				},
				fail: () => {
					uni.showToast({
						icon: "none",
						title: "获取点赞数失败"
					});
				},
			});
		},
		getLikeStatus(id) {
			uni.request({
				url: `http://localhost:8080/getLikeStatus`,
				method: 'GET',
				header: {
					'Authorization': this.token
				},
				data: {
					userId: this.user.userId,
					postId: id,
				},
				success: (res) => {
					this.likeStatus = res.data.data;
					console.log("likeStatus:",this.likeStatus);
				},
				fail: () => {
					uni.showToast({
						icon: "none",
						title: "获取点赞状态失败"
					});
				},
			});
		},
		getFavoriteNum(id) {
			uni.request({
				url: `http://localhost:8080/getFavoriteCount`,
				method: 'GET',
				header: {
					'Authorization': this.token
				},
				data: {
					postId: id,
				},
				success: (res) => {
					this.favoriteNum = res.data.data;
					console.log("favoriteNum:",this.favoriteNum);
				},
				fail: () => {
					uni.showToast({
						icon: "none",
						title: "获取收藏数失败"
					});
				},
			});
		},
		getFavoriteStatus(id) {
			uni.request({
				url: `http://localhost:8080/getFavoriteStatus`,
				method: 'GET',
				header: {
					'Authorization': this.token
				},
				data: {
					userId: this.user.userId,
					postId: id,
				},
				success: (res) => {
					this.favoriteStatus = res.data.data;
					console.log("favoriteStatus:",this.favoriteStatus);
				},
				fail: () => {
					uni.showToast({
						icon: "none",
						title: "获取收藏状态失败"
					});
				},
			});
		},
		getComments(id) {
			// 获取该帖子的所有评论
			uni.request({
				url: `http://localhost:8080/getCommentList`,
				method: 'GET',
				header: {
					'Authorization': this.token,
				},
				data: {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					postId: id,
				},
				success: (res) => {
					uni.stopPullDownRefresh();
					console.log("res.data:",res.data);
					this.comments = res.data.data.records;
					console.log("comments:",this.comments);
				},
				fail: () => {
					uni.showToast({
						icon: "none",
						title: "获取评论信息失败"
					});
				},
			});
		},
		getTotalPage(id) {
			this.status = '正在加载';
			const token = this.token;
			if(!token) {
				uni.showToast({
					icon: "none",
					title: '请先登录'
				});
				return;
			}
			uni.request({
				url: "http://localhost:8080/getCommentTotalPage",
				method: "GET",
				data: {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					postId: id,
				},
				header: {
					'Authorization':token
				},
				success: (res) => {
					console.log("res.data:",res.data);
					console.log("res.data.data.pages:",res.data.data.pages);
					if (res.data.code === 200) {
						this.totalPage = res.data.data.pages + 1;
					} else {
						uni.showToast({
							icon: "none",
							title: "获取分页数操作失败"
						});
					}
				},
				fail: () => {},
				complete: () => {}
			});
		},
		showCommentMenu(comment) {
			if (comment.userId == this.user.userId) {
				this.selectedComment = comment;
				this.$refs.commentMenuPopup.open();
			}
			else {
				uni.showToast({
					icon: "none",
					title: '非当前用户发表的评论不可操作'
				});
				return;
			}
		},
		deleteComment(id) {
			const token = this.token;
			if(!token) {
				uni.showToast({
					icon: "none",
					title: '请先登录'
				});
				return;
			}
			uni.request({
				url: "http://localhost:8080/deleteComment",
				method: "POST",
				data: {
					commentId: id
				},
				header: {
					'Authorization':token,
					'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
				},
				success: (res) => {
					if (res.data.code == 200) {
						uni.showToast({
							icon: "none",
							title: '删除成功'
						});
						this.getComments(this.post.postId);
					}
					else {
						uni.showToast({
							icon: "none",
							title: "删除失败，请稍后再试"
						});
					}
				},
				fail: () => {
					uni.showToast({
						icon: "none",
						title: "网络错误"
					});
				},
			});
		},
		likePost() {
			// 点赞逻辑
			uni.request({
				url: `http://localhost:8080/like`,
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
					'Authorization': this.token,
				},
				data: {
					postId: this.post.postId,
					userId: this.user.userId,
				},
				success: (res) => {
					if (res.data.code === 200) {
						this.likeStatus = !this.likeStatus;
						if (this.likeStatus) {
							this.likeNum += 1;
						} else {
							this.likeNum -= 1;
						}
					} else {
						uni.showToast({
							icon: "none",
							title: "点赞操作失败"
						});
					}
				},
				fail: () => {
					uni.showToast({
						icon: "none",
						title: "点赞操作失败"
					});
				},
			});
		},
		favoritePost() {
			// 收藏逻辑
			uni.request({
				url: `http://localhost:8080/favorite`,
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
					'Authorization': this.token,
				},
				data: {
					postId: this.post.postId,
					userId: this.user.userId,
				},
				success: (res) => {
					if (res.data.code === 200) {
						this.favoriteStatus = !this.favoriteStatus;
						if (this.favoriteStatus) {
							this.favoriteNum += 1;
						} else {
							this.favoriteNum -= 1;
						}
					} else {
						uni.showToast({
							icon: "none",
							title: "收藏操作失败"
						});
					}
				},
				fail: () => {
					uni.showToast({
						icon: "none",
						title: "收藏操作失败"
					});
				},
			});
		},
		submitComment() {
			// 提交新评论
			if (this.newCommentText.trim()) {
				uni.request({
					url: 'http://localhost:8080/addComment',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
						'Authorization': this.token
					},
					data: {
						userId: this.user.userId,
						postId: this.post.postId,
						content: this.newCommentText
					},
					success: (res) => {
						if (res.statusCode === 200) {
							this.newCommentText = '';
							this.getComments(this.post.postId); // 更新评论列表
						} else {
							console.error('Failed to add comment');
						}
					}
				});
			}
		},
		formatDate(date) {
			const options = {
				year: 'numeric',
				month: 'long',
				day: 'numeric',
				hour: '2-digit',
				minute: '2-digit',
				hour12: false
			};
			return new Date(date).toLocaleDateString(undefined, options);
		},
		toBack() {
			uni.navigateBack({
				delta: 1
			});
		},
		formatCount(num) {
			if (num >= 1000) {
				return (num / 1000).toFixed(1) + ' k';
			}
			return num;
		}
	}
}
</script>

<style scoped lang="scss">
.post-detail {
  .navBar {
    display: flex;
    height: 100rpx;
    background-color: white;
    align-items: center;
    padding: 0 30rpx;

    .left {
      flex: 1;
    }

    .center {
      flex: 1;
      color: #646566;
      text-align: center;
      font-size: 34rpx;
      font-weight: 700;
    }

    .right {
      flex: 1;
    }
  }

  .post-content {
    padding: 20rpx;

    .post-header {
      margin-bottom: 20rpx;

      .post-title {
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }

      .post-meta {
        font-size: 24rpx;
        color: #999;
      }
    }

    .post-body {
      font-size: 30rpx;
      color: #666;
      margin-bottom: 20rpx;
      white-space: pre-line;
    }

    .interaction-buttons {
		display: flex;
		margin-bottom: 20rpx;

		.interaction-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-right: 20rpx;

			text {
				font-size: 28rpx;
				color: #666;
				margin-top: 5rpx;
			}
		}
	}

    .comments-section {
      .comment-item {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
      }

      .add-comment {
        display: flex;
        align-items: center;

        input {
          flex: 1;
          padding: 10rpx;
          border: 1rpx solid #ccc;
          border-radius: 5rpx;
          margin-right: 10rpx;
        }

        button {
          padding: 10rpx 20rpx;
        }
      }
    }
  }
	.comment-actions {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		
		.more-options {
			text-align: right;
			font-size: 28rpx;
			color: #999;
		}
	}
	
	.popup-menu {
		width: 100%;
		padding: 20rpx;
		background-color: white;
		
		button {
			width: 100%;
			margin-bottom: 20rpx;
			background-color: #1296db;
			color: white;
			border: none;
			padding: 10rpx 20rpx;
			border-radius: 5rpx;
		}
	}
}
</style>